package org.example.service;

import lombok.RequiredArgsConstructor;
import org.example.domain.Book;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class BookService {

//    private final BookRepository bookRepository;

    private static Map<Integer, Book> map = new HashMap<>();

    @Cacheable(value = "book", key = "#id")// 定义缓存的键为方法参数，值是方法的返回值
    public Book findBookById(int id) { // 查找一本书
        System.out.println("从数据库中查找ID为" + id + "的书，并添加到缓存，key为" + id);
        return map.getOrDefault(id, new Book());
    }

    @CachePut(value = "book", key = "#book.id")// 定义缓存的键为参数book对象的id属性，值为方法返回值
    public Book addBook(Book book) { // 添加一本书
        System.out.println("添加一本书到数据库，同时添加到缓存");
        return map.put(book.getId(), book);

    }

    @CacheEvict(value = "book", key = "#id")// 根据参数指定的键删除缓存
    public void deleteBookById(int id) {
        System.out.println("从数据库中删除一本书，同时删除key为" + id + "的缓存");
        map.remove(id);
    }

    @CachePut(value = "book", key = "#book.id") // 修改缓存
    public Book updateBook(Book book) { // 修改一本书
        System.out.println("更新数据库中的书，同时更新缓存,key为" + book.getId());
        return map.put(book.getId(), book);
    }
}
